package com.ys.web.mobao.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.ys.base.EnumType;
import com.ys.utils.alipay.AliPayHandler;
import com.ys.utils.alipay.config.YsAlipayConfig;
import com.ys.utils.alipay.model.MsgInfo;
import com.ys.utils.annotation.RiskValidation;
import com.ys.utils.annotation.UserGroupNumberCheck;
import com.ys.utils.annotation.UserWithdrawBlack;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.*;
import com.ys.utils.hjzf.HjzfHandler;
import com.ys.utils.http.RSAUtils;
import com.ys.utils.mobao.MobaoPay;
import com.ys.utils.pay.Result;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.ali.manager.YsAlipayConfigManager;
import com.ys.web.mobao.model.po.MobaoWithholdingCreate;
import com.ys.web.mobao.model.po.Notify;
import com.ys.web.mobao.service.MobaoWithholdingService;
import com.ys.web.pay.PayEnum;
import com.ys.web.pay.PayService;
import com.ys.web.pay.manager.PayManager;
import com.ys.web.pay.model.WithdrawRecord;
import com.ys.web.pay.model.WithdrawRecordWait;
import com.ys.web.pay.model.vo.UserBank;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import com.ys.web.user.risk.Risk;
import com.ys.web.user.risk.RiskService;
import com.ys.web.yinsheng.model.RequestData;
import com.ys.web.yinsheng.model.UserMerchant;
import com.ys.web.yinsheng.service.YinShengService;
import com.ys.web.yinsheng.util.ServiceEnum;
import com.ys.web.yinsheng.util.YinShengClient;
import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/onlinePay/transferDomestic/single/order/")
public class MobaoWithholdingController {
    @Autowired
    private PayService payService;
    @Autowired
    private MobaoWithholdingService mobaoWithholdingService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private RiskService riskService;

    @Autowired
    private YinShengService yinShengService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private YsAlipayConfigManager ysAlipayConfigManager;

    /**
     * @作者: dhf
     * @名称: 摩宝提现
     * @param ip
     * @param uid
     * @param withholdingCreate
     * @时间: 2022/9/7 20:48
     * @备注:
     * @返回值: java.lang.String
     */

    @UserWithdrawBlack
    @UserGroupNumberCheck
    @RiskValidation
    @RequestMapping("create/mb")
    public String createMb(@RequestAttribute String ip, @RequestAttribute Long uid, MobaoWithholdingCreate withholdingCreate) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        HttpUtil.userIpAdds(ip);
        withholdingCreate.payChannel=StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        // 数据验证
        withholdingCreate.check(uid+"");

        String limitKey = UserKey.withholdingCreateKeyLimit(uid);
        if(Redis.key.exists(limitKey)){
            SystemError.wrapBs("400","提现间隔不能小于"+StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time"))/60+"分钟");
        }

        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.withholdingCreateKey(dayKey, uid);
        if (Redis.key.exists(key)) {
            String count = Redis.str.get(key);
            String setCount = Config.pp.get("wallet.withholding.money.day.num");
            if (Convert.objToInt(count) >= Convert.objToInt(setCount)) {
                SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "提现失败，每日最多提现" + setCount + "次");
            }
        }

        if(Config.pp.getOrDefault("wallet.account.balance","true").equals("true")){
            String balance = MobaoPay.balanceQuery();
            if(StringHandler.getLong(withholdingCreate.getAmount())>StringHandler.yuanToFen(balance)){
                SystemError.wrapBs("500","支付通道限额，请次日提现");
            }
        }

        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));

        if (!PayManager.validatePayPassword(RSAUtils.decryptField(withholdingCreate.getPayPassword()), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }

        UserBank userBank = payService.getUserBankByUserIdMb(uid,withholdingCreate.getCardToken());
        if(StringHandler.isEmpty(userBank)){
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
        }
//        if(!userVo.getRealName().equals(userBank.getUserName())){
//            Logger.error(String.format("提现申请信息异常需查看uid:%s,cardToken:%s",uid,withholdingCreate.getCardToken()));
//            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "实名信息异常，请截图并联系客服");
//        }
        if(withholdingCreate.isWait() && mobaoWithholdingService.getUserWhiteByUid(uid)==1){
            withholdingCreate.setWait(false);
        }
        //设置实际到账金额
        BigDecimal bArrival = new BigDecimal(withholdingCreate.getAmount());
        //费率
        BigDecimal rate = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.ratio"),"300")).divide(new BigDecimal(10000));
        //额外手续费
        BigDecimal extraMoney = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.extra"),"3000")).divide(new BigDecimal(10));

        BigDecimal arrival = bArrival.subtract(bArrival.multiply(rate)).subtract(extraMoney);
        withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.intValue()));
        //验证是否在 免手续费提现次数
        int setFreeCount = StringHandler.getInt(Config.pp.get("wallet.withholding.money.free.num"));
        String freeKey = UserKey.withholdingFreeKey(dayKey, uid);
        int freeCount = StringHandler.getInt(Redis.str.get(freeKey));
        if (freeCount < setFreeCount) {
            //免手续费最小金额
            long freeMoneyMin = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.min"));
            //免手续费最大金额
            long freeMoneyMax = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.max"));
            //提现金额
            long money = StringHandler.fenToLi(withholdingCreate.getAmount());
            if (money >= freeMoneyMin && money <= freeMoneyMax) {
                withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.add(extraMoney).intValue()));
                withholdingCreate.setNoFee(1);
            }
        }

        WithdrawRecordWait record = new WithdrawRecordWait();
        record.setUserId(uid);
        record.setAmount(StringHandler.getLong(withholdingCreate.getAmount()));
        record.setFee(StringHandler.getLong(withholdingCreate.getAmount())-StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawAmount(StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawStatus(PayEnum.WithdrawStatus.APPLY_WITHDRAWAL.getCode());
        record.setOrderNo(withholdingCreate.getRequestId());
        // 银行卡信息
        record.setMobile(userBank.getMobile());
        record.setUserName(userBank.getUserName());
        record.setCardNo(userBank.getCardNo());
        record.setBankName(userBank.getBankName());
        record.payChannel = 2;
        record.taskTime = StringHandler.getLong(DateHandler.getMinute(StringHandler.getInt(Config.pp.get("wallet.withholding.task.time"),30)));
        record.taskType = 2;
        record.ip = ip;
        record.setNoFee(withholdingCreate.getNoFee());
        // 动账操作
        Result<?> result = PayManager.accountModify(uid, PayEnum.AccountFlowType.APPLY_FOR_WITHDRAWAL, record.getAmount(),
                String.format("余额提现-到%s(%s)",userBank.getBankName(),userBank.getCardNo().substring(userBank.getCardNo().length()-4)),1);
        if (!result.success()) {
            SystemError.wrapBs("500",result.getMessage());
        }
        if(mobaoWithholdingService.getWithdrawRecordWaitCountByUid(uid)>0 || !withholdingCreate.isWait()){
            // 银行卡提现操作
            try {
                if(StringHandler.getInt(Config.pp.get("wallet.withholding.task.open"),0)==0) {
                    record.taskType = 1;
                    com.alibaba.fastjson.JSONObject data = MobaoPay.withdraw(ip, key, withholdingCreate, userBank);
                    if (data.getString("orderStatus").equals("00")) {
                        //提现成功扣除冻结金额
//                        PayManager.accountModify(record.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, record.getAmount(), StringHandler.getString(record.getUserId()));
                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                        Redis.key.increment(key);
                        Redis.key.setKeyTimeout(key, 86400L);
                        Redis.key.increment(freeKey);
                        Redis.key.setKeyTimeout(freeKey, 86400L);
                    } else if (data.getString("orderStatus").equals("09")) {
                        Redis.key.increment(freeKey);
                        Redis.key.setKeyTimeout(freeKey, 86400L);
                    } else {
                        //提现失败退回余额
                        PayManager.accountModify(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), data.getString("remark"),1);
                        // 保存提现记录
                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                        record.setRemark(data.getString("remark"));
                        mobaoWithholdingService.saveWithdrawRecord(record);
                        SystemError.wrapBs("400", "提现失败,请核对并修改正确的信息后再试");
                    }
                }
                // 保存提现记录
                mobaoWithholdingService.saveWithdrawRecord(record);
            } catch (Exception e) {
                //提现失败退回余额
                PayManager.accountModify(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), e.getMessage(),1);
                // 保存提现记录
                record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                record.setRemark(e.getMessage());
                mobaoWithholdingService.saveWithdrawRecord(record);
                Logger.error("提现失败:",e);
                SystemError.wrapBs("400","提现失败，请核对并修改正确的信息后再试.");
            }
        }else {
            // 保存提现记录
            record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode());
            mobaoWithholdingService.saveWithdrawRecord(record);
            record.setWithdrawStatus(PayEnum.WithdrawWaitStatus.APPLY_WITHDRAWAL.getCode());
            record.setCardToken(userBank.getCardToken());
            mobaoWithholdingService.saveWithdrawRecordWait(record);
        }
        Redis.str.set(limitKey,"1",StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time")));
        return ResponseHandler.success(withholdingCreate.getRequestId());
    }

    @UserWithdrawBlack
    @UserGroupNumberCheck
    @RiskValidation
    @RequestMapping("create/zfb")
    public String createZfb(@RequestAttribute String ip, @RequestAttribute Long uid, MobaoWithholdingCreate withholdingCreate) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        if(!withholdingCreate.whiteList(uid+"")) {
            if (Boolean.parseBoolean(Config.pp.get("wallet.account.ali.withdraw"))) {
                SystemError.wrapBs("500", "提现功能暂时已关闭");
            }
        }
        HttpUtil.userIpAdds(ip);
        withholdingCreate.payChannel=StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        // 数据验证
        withholdingCreate.check(uid+"");

        String limitKey = UserKey.withholdingCreateKeyLimit(uid);
        if(Redis.key.exists(limitKey)){
            SystemError.wrapBs("400","提现间隔不能小于"+StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time"))/60+"分钟");
        }

        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.withholdingCreateKey(dayKey, uid);
        String zfbMoneyDayAllKey = UserKey.withholdingFreeDayKey(dayKey);
        String zfbAllMoney = Redis.str.get(zfbMoneyDayAllKey);
        if(!withholdingCreate.whiteList(uid+"")) {
            if (Redis.key.exists(key)) {
                String count = Redis.str.get(key);
                String setCount = Config.pp.get("wallet.withholding.money.day.num");
                if (Convert.objToInt(count) >= Convert.objToInt(setCount)) {
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "提现失败，每日最多提现" + setCount + "次");
                }
            }
            //按照元计算
            if (StringHandler.isNotEmpty(zfbAllMoney)) {
                long zfb = StringHandler.getLong(Config.pp.get("wallet.withholding.money.zfb.day.all"));
                if (zfb > 0) {
                    if (StringHandler.getLong(StringHandler.isEmpty(zfbAllMoney) ? 0 : StringHandler.getLong(zfbAllMoney)) + (StringHandler.getLong(withholdingCreate.getAmount()) / 100) > zfb) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "支付通道限额，请次日提现");
                    }
                }
            }
        }
        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(withholdingCreate.getPayPassword()), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        if(withholdingCreate.isWait() && mobaoWithholdingService.getUserWhiteByUid(uid)==1){
            withholdingCreate.setWait(false);
        }
        if(StringHandler.isEmpty(userVo.alipayUid)){
            SystemError.wrapBs("500", "请绑定支付宝");
        }
        //设置实际到账金额
        BigDecimal bArrival = new BigDecimal(withholdingCreate.getAmount());
        //费率
        BigDecimal rate = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.ratio"),"300")).divide(new BigDecimal(10000));
        //额外手续费
        BigDecimal extraMoney = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.extra"),"3000")).divide(new BigDecimal(10));

        BigDecimal arrival = bArrival.subtract(bArrival.multiply(rate)).subtract(extraMoney);
        withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.intValue()));
        //验证是否在 免手续费提现次数
        int setFreeCount = StringHandler.getInt(Config.pp.get("wallet.withholding.money.free.num"));
        String freeKey = UserKey.withholdingFreeKey(dayKey, uid);
        int freeCount = StringHandler.getInt(Redis.str.get(freeKey));
        if (freeCount < setFreeCount) {
            //免手续费最小金额
            long freeMoneyMin = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.min"));
            //免手续费最大金额
            long freeMoneyMax = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.max"));
            //提现金额
            long money = StringHandler.fenToLi(withholdingCreate.getAmount());
            if (money >= freeMoneyMin && money <= freeMoneyMax) {
                withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.add(extraMoney).intValue()));
                withholdingCreate.setNoFee(1);
            }
        }

        WithdrawRecordWait record = new WithdrawRecordWait();
        record.setUserId(uid);
        record.setAmount(StringHandler.getLong(withholdingCreate.getAmount()));
        record.setFee(StringHandler.getLong(withholdingCreate.getAmount())-StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawAmount(StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawStatus(PayEnum.WithdrawStatus.APPLY_WITHDRAWAL.getCode());
        record.setOrderNo(withholdingCreate.getRequestId());
        record.setCardNo(userVo.alipayUid);
        //支付宝信息
        record.payChannel = 4;
        record.taskTime = StringHandler.getLong(DateHandler.getMinute(StringHandler.getInt(Config.pp.get("wallet.withholding.task.time"),30)));
        record.taskType = 2;
        record.ip = ip;
        record.setNoFee(withholdingCreate.getNoFee());
        // 动账操作
        Result<?> result = PayManager.accountModifyZfb(uid, PayEnum.AccountFlowType.APPLY_FOR_WITHDRAWAL, record.getAmount(),
                String.format("余额提现-到%s","支付宝"));
        if (!result.success()) {
            SystemError.wrapBs("500",result.getMessage());
        }

        if(mobaoWithholdingService.getWithdrawRecordWaitCountByUid(uid)>0 || !withholdingCreate.isWait()){
            // 支付宝提现操作
            try {
                YsAlipayConfig ysAlipayConfig = null;
                if(!Boolean.parseBoolean(Config.pp.get("ys.ali.pay.appid.all.open"))) {
                    List<String> obj = JSONObject.parseArray(Config.pp.get("ys.apipay.appid"),String.class);
                    record.appid = obj.get(0);
                }else{
                    ysAlipayConfig = ysAlipayConfigManager.getAppIdWith();
                    if(StringHandler.isEmpty(ysAlipayConfig)){
                        log.error("支付失败----------ysAlipayConfig--------为空");
                        SystemError.wrapBs("500", "支付失败");
                    }
                    if(StringHandler.isEmpty(ysAlipayConfig.appId)){
                        log.error("支付失败----------appid--------为空");
                        SystemError.wrapBs("500", "支付失败");
                    }
                    record.appid = ysAlipayConfig.appId;
                }
                if(StringHandler.getInt(Config.pp.get("wallet.withholding.task.open"),0)==0) {
                    record.taskType = 1;
                    AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
                    model.setOutBizNo(record.orderNo);
                    model.setRemark(record.getRemark());
                    model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
                    model.setBizScene("DIRECT_TRANSFER");
                    Participant payeeInfo = new Participant();
                    payeeInfo.setIdentity(userVo.alipayUid);
//                    payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
                    payeeInfo.setIdentityType("ALIPAY_USER_ID");
                    model.setPayeeInfo(payeeInfo);
                    model.setTransAmount(StringHandler.fenToYuan(record.withdrawAmount+""));
                    model.setProductCode("TRANS_ACCOUNT_NO_PWD");
                    model.setOrderTitle(record.getRemark());
                    MsgInfo msgInfo = null;
                    AliPayHandler aliPayHandler = null;
                    if(!Boolean.parseBoolean(Config.pp.get("ys.ali.pay.appid.all.open"))){
                        aliPayHandler = new AliPayHandler(Config.pp);
                    }else{
                        aliPayHandler = new AliPayHandler(ysAlipayConfig);
                    }
                    msgInfo = aliPayHandler.trans(record.appid,model);
                    log.info("支付宝转账---------------"+ Json.toJson(msgInfo));
                    if(msgInfo.isSuccess){
                        record.orderOutNo =  msgInfo.thirdOrder;
                        record.payFundOrderId = msgInfo.payFundOrderId;
                        record.withdrawStatus = PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode();
                        record.dayKey = dayKey+"";
                        Redis.key.increment(key);
                        Redis.key.setKeyTimeout(key, 86400L);
                        Redis.key.increment(freeKey);
                        Redis.key.increment(zfbMoneyDayAllKey,StringHandler.getLong(withholdingCreate.getAmount())/100);
                        Redis.key.setKeyTimeout(zfbMoneyDayAllKey,24*60*60L);
                        Redis.key.setKeyTimeout(freeKey, 86400L);
                    } else {
                        ///提现失败退回余额
                        PayManager.accountModifyZfb(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), msgInfo.errMsg);
                        // 保存提现记录
                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                        record.setRemark(msgInfo.errMsg);
                        mobaoWithholdingService.saveWithdrawRecord(record);
                        SystemError.wrapBs("400", "提现失败,请核对并修改正确的信息后再试");
                    }
                }else{
                    Redis.key.increment(zfbMoneyDayAllKey,StringHandler.getLong(withholdingCreate.getAmount())/100);
                    Redis.key.setKeyTimeout(zfbMoneyDayAllKey,24*60*60L);
                }
                // 保存提现记录
                mobaoWithholdingService.saveWithdrawRecord(record);
            } catch (Exception e) {
                //提现失败退回余额
                PayManager.accountModifyZfb(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), e.getMessage());
                // 保存提现记录
                record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                record.setRemark(e.getMessage());
                mobaoWithholdingService.saveWithdrawRecord(record);
                Logger.error("提现失败:",e);
                SystemError.wrapBs("400","提现失败，请核对并修改正确的信息后再试.");
            }
        }else {
            // 保存提现记录
            record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode());
            mobaoWithholdingService.saveWithdrawRecord(record);
            record.setWithdrawStatus(PayEnum.WithdrawWaitStatus.APPLY_WITHDRAWAL.getCode());
            mobaoWithholdingService.saveWithdrawRecordWait(record);
        }
        Redis.str.set(limitKey,"1",StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time")));
        return ResponseHandler.success(withholdingCreate.getRequestId());
    }

    @UserWithdrawBlack
    @UserGroupNumberCheck
    @RiskValidation
    @RequestMapping("create/hjzf")
    public String createHjzf(@RequestAttribute String ip, @RequestAttribute Long uid, MobaoWithholdingCreate withholdingCreate) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        if(!withholdingCreate.whiteList(uid+"")) {
            if (Boolean.parseBoolean(Config.pp.get("wallet.account.hjzf.withdraw"))) {
                SystemError.wrapBs("500", "提现功能暂时已关闭");
            }
        }
        HttpUtil.userIpAdds(ip);
        // 数据验证
        withholdingCreate.check(uid+"");
        String limitKey = UserKey.withholdingCreateKeyLimit("hjzf:"+uid);
        if(Redis.key.exists(limitKey)){
            SystemError.wrapBs("400","提现间隔不能小于"+StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time"))/60+"分钟");
        }
        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.withholdingCreateKey(dayKey, uid);
        String hjzfMoneyDayAllKey = UserKey.withholdingFreeDayKey(dayKey);
        String hjzfAllMoney = Redis.str.get(hjzfMoneyDayAllKey);
        if(!withholdingCreate.whiteList(uid+"")) {
            if (Redis.key.exists(key)) {
                String count = Redis.str.get(key);
                String setCount = Config.pp.get("wallet.withholding.hjzf.money.day.num");
                if (Convert.objToInt(count) >= Convert.objToInt(setCount)) {
                    SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "提现失败，每日最多提现" + setCount + "次");
                }
            }

            //按照元计算
            if (StringHandler.isNotEmpty(hjzfAllMoney)) {
                long hjzf = StringHandler.getLong(Config.pp.get("wallet.withholding.money.hjzf.day.all"));
                if (hjzf > 0) {
                    if (StringHandler.getLong(StringHandler.isEmpty(hjzfAllMoney) ? 0 : StringHandler.getLong(hjzfAllMoney)) + (StringHandler.getLong(withholdingCreate.getAmount()) / 100) > hjzf) {
                        SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "支付通道限额，请次日提现");
                    }
                }
            }
        }
        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));
        if (!PayManager.validatePayPassword(RSAUtils.decryptField(withholdingCreate.getPayPassword()), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }
        if(withholdingCreate.isWait() && mobaoWithholdingService.getUserWhiteByUid(uid)==1){
            withholdingCreate.setWait(false);
        }
        UserBank userBank = payService.getUserBankHjzfByUserId(uid,withholdingCreate.getCardToken());
        if(StringHandler.isEmpty(userBank)){
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
        }
        //设置实际到账金额
        BigDecimal bArrival = new BigDecimal(withholdingCreate.getAmount());
        //费率
        BigDecimal rate = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.hjzf.money.fee.ratio"),"300")).divide(new BigDecimal(10000));
        //额外手续费
        BigDecimal extraMoney = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.hjzf.money.fee.extra"),"3000")).divide(new BigDecimal(10));

        BigDecimal arrival = bArrival.subtract(bArrival.multiply(rate)).subtract(extraMoney);
        withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.intValue()));
        //验证是否在 免手续费提现次数
        int setFreeCount = StringHandler.getInt(Config.pp.get("wallet.withholding.money.free.num"));
        String freeKey = UserKey.withholdingFreeKey(dayKey, uid);
        int freeCount = StringHandler.getInt(Redis.str.get(freeKey));
        if (freeCount < setFreeCount) {
            //免手续费最小金额
            long freeMoneyMin = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.min"));
            //免手续费最大金额
            long freeMoneyMax = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.max"));
            //提现金额
            long money = StringHandler.fenToLi(withholdingCreate.getAmount());
            if (money >= freeMoneyMin && money <= freeMoneyMax) {
                withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.add(extraMoney).intValue()));
                withholdingCreate.setNoFee(1);
            }
        }

        WithdrawRecordWait record = new WithdrawRecordWait();
        record.setUserId(uid);
        record.setAmount(StringHandler.getLong(withholdingCreate.getAmount()));
        record.setFee(StringHandler.getLong(withholdingCreate.getAmount())-StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawAmount(StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawStatus(PayEnum.WithdrawStatus.APPLY_WITHDRAWAL.getCode());
        record.setOrderNo(withholdingCreate.getRequestId());
        record.setCardNo(userBank.cardNo);
        record.setMobile(userBank.mobile);
        record.setUserName(userBank.userName);
        //支付宝信息
        record.payChannel = 5;
        record.taskTime = StringHandler.getLong(DateHandler.getMinute(StringHandler.getInt(Config.pp.get("wallet.withholding.task.time"),30)));
        record.taskType = 2;
        record.ip = ip;
        record.setNoFee(withholdingCreate.getNoFee());
        // 动账操作
        Result<?> result = PayManager.accountModifyHjzf(uid, PayEnum.AccountFlowType.APPLY_FOR_WITHDRAWAL, record.getAmount(),
                String.format("余额提现-到%s","银行卡"));
        if (!result.success()) {
            SystemError.wrapBs("500",result.getMessage());
        }
        if(mobaoWithholdingService.getWithdrawRecordWaitCountByUid(uid)>0 || !withholdingCreate.isWait()){
            // 支付宝提现操作
            try {
                if(StringHandler.getInt(Config.pp.get("wallet.withholding.task.open"),0)==0) {
                    record.taskType = 1;
                    log.info("汇聚支付转账---------------"+ Json.toJson(1));
                    MsgInfo msgInfo = HjzfHandler.trans(record);
                    if(!msgInfo.isSuccess){
                        ///提现失败退回余额
                        PayManager.accountModifyHjzf(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), msgInfo.errMsg);
                        // 保存提现记录
                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                        record.setRemark(msgInfo.errMsg);
                        mobaoWithholdingService.saveWithdrawRecord(record);
                        SystemError.wrapBs("400", "提现失败,请核对并修改正确的信息后再试");
                    }
                    Redis.key.increment(hjzfMoneyDayAllKey,StringHandler.getLong(withholdingCreate.getAmount())/100);
                    Redis.key.setKeyTimeout(hjzfMoneyDayAllKey,24*60*60L);
                }else{
                    Redis.key.increment(hjzfMoneyDayAllKey,StringHandler.getLong(withholdingCreate.getAmount())/100);
                    Redis.key.setKeyTimeout(hjzfMoneyDayAllKey,24*60*60L);
                }
                // 保存提现记录
                mobaoWithholdingService.saveWithdrawRecord(record);
            } catch (Exception e) {
                //提现失败退回余额
                PayManager.accountModifyHjzf(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), e.getMessage());
                // 保存提现记录
                record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                record.setRemark(e.getMessage());
                mobaoWithholdingService.saveWithdrawRecord(record);
                Logger.error("提现失败:",e);
                SystemError.wrapBs("400","提现失败，请核对并修改正确的信息后再试.");
            }
        }else {
            // 保存提现记录
            record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode());
            mobaoWithholdingService.saveWithdrawRecord(record);
            record.setWithdrawStatus(PayEnum.WithdrawWaitStatus.APPLY_WITHDRAWAL.getCode());
            mobaoWithholdingService.saveWithdrawRecordWait(record);
        }
        Redis.str.set(limitKey,"1",StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time")));
        return ResponseHandler.success(withholdingCreate.getRequestId());
    }
    /**
     * 提现预下单
     *
     * @param uid
     * @param withholdingCreate
     * @return
     */

    @UserWithdrawBlack
    @UserGroupNumberCheck
    @RiskValidation
    @RequestMapping("create")
    public String create(@RequestAttribute String ip, @RequestAttribute Long uid, MobaoWithholdingCreate withholdingCreate) {
        if (Boolean.parseBoolean(Config.pp.get("trading.disable"))) {
            SystemError.wrapBs("500", "系统维护,交易系统已关闭");
        }
        withholdingCreate.payChannel=StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        // 数据验证
        withholdingCreate.check(uid+"");

        String limitKey = UserKey.withholdingCreateKeyLimit(uid);
        if(Redis.key.exists(limitKey)){
            SystemError.wrapBs("400","提现间隔不能小于"+StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time"))/60+"分钟");
        }

        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.withholdingCreateKey(dayKey, uid);
        if (Redis.key.exists(key)) {
            String count = Redis.str.get(key);
            String setCount = Config.pp.get("wallet.withholding.money.day.num");
            if (Convert.objToInt(count) >= Convert.objToInt(setCount)) {
                SystemError.wrapBs(EnumType.ResponseCode.Fail.getCode(), "提现失败，每日最多提现" + setCount + "次");
            }
        }

        if(Config.pp.getOrDefault("wallet.account.balance","true").equals("true")){
            String balance = MobaoPay.balanceQuery();
            if(StringHandler.getLong(withholdingCreate.getAmount())>StringHandler.yuanToFen(balance)){
                SystemError.wrapBs("500","支付通道限额，请次日提现");
            }
        }

        LoginInfo userVo = loginService.infoByUid(StringHandler.getString(uid));

        if (!PayManager.validatePayPassword(RSAUtils.decryptField(withholdingCreate.getPayPassword()), userVo)) {
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "支付密码错误");
        }

        UserBank userBank = payService.getUserBankByUserId(uid,withholdingCreate.getCardToken());

        if(StringHandler.isEmpty(userBank)){
            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "银行卡不存在");
        }

//        if(!userVo.getRealName().equals(userBank.getUserName())){
//            Logger.error(String.format("提现申请信息异常需查看uid:%s,cardToken:%s",uid,withholdingCreate.getCardToken()));
//            SystemError.wrapBs(EnumType.ResponseCode.ILLEGAL.getCode(), "实名信息异常，请截图并联系客服");
//        }
        if(withholdingCreate.isWait() && mobaoWithholdingService.getUserWhiteByUid(uid)==1){
            withholdingCreate.setWait(false);
        }
        //设置实际到账金额
        BigDecimal bArrival = new BigDecimal(withholdingCreate.getAmount());
        //费率
        BigDecimal rate = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.ratio"),"300")).divide(new BigDecimal(10000));
        //额外手续费
        BigDecimal extraMoney = new BigDecimal(StringHandler.getString(Config.pp.get("wallet.withholding.money.fee.extra"),"3000")).divide(new BigDecimal(10));

        BigDecimal arrival = bArrival.subtract(bArrival.multiply(rate)).subtract(extraMoney);
        withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.intValue()));
        //验证是否在 免手续费提现次数
        int setFreeCount = StringHandler.getInt(Config.pp.get("wallet.withholding.money.free.num"));
        String freeKey = UserKey.withholdingFreeKey(dayKey, uid);
        int freeCount = StringHandler.getInt(Redis.str.get(freeKey));
        if (freeCount < setFreeCount) {
            //免手续费最小金额
            long freeMoneyMin = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.min"));
            //免手续费最大金额
            long freeMoneyMax = StringHandler.getLong(Config.pp.get("wallet.withholding.money.free.max"));
            //提现金额
            long money = StringHandler.fenToLi(withholdingCreate.getAmount());
            if (money >= freeMoneyMin && money <= freeMoneyMax) {
                withholdingCreate.setArrivalAmount(StringHandler.getString(arrival.add(extraMoney).intValue()));
                withholdingCreate.setNoFee(1);
            }
        }

        WithdrawRecordWait record = new WithdrawRecordWait();
        record.setUserId(uid);
        record.setAmount(StringHandler.getLong(withholdingCreate.getAmount()));
        record.setFee(StringHandler.getLong(withholdingCreate.getAmount())-StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawAmount(StringHandler.getLong(withholdingCreate.getArrivalAmount()));
        record.setWithdrawStatus(PayEnum.WithdrawStatus.APPLY_WITHDRAWAL.getCode());
        record.setOrderNo(withholdingCreate.getRequestId());
        // 银行卡信息
        record.setMobile(userBank.getMobile());
        record.setUserName(userBank.getUserName());
        record.setCardNo(userBank.getCardNo());
        record.setBankName(userBank.getBankName());
        record.setNoFee(withholdingCreate.getNoFee());
        //银盛提现
        if(withholdingCreate.payChannel.equals("ys")){
            withholdingCreate.notifyUrl = withholdingCreate.ys_otifyUrl;
            record.payChannel = 1;
            record.taskTime = StringHandler.getLong(DateHandler.getMinute(StringHandler.getInt(Config.pp.get("wallet.withholding.task.time"),30)));
            record.setCardToken(userBank.getCardToken());
            record.linkId=userBank.linkId;
            record.taskType = 2;
            return this.ysWithholding(uid,withholdingCreate,record,ip,userBank.linkId,limitKey);
        }
        // 动账操作
        Result<?> result = PayManager.accountModify(uid, PayEnum.AccountFlowType.APPLY_FOR_WITHDRAWAL, record.getAmount(),
                String.format("余额提现-到%s(%s)",userBank.getBankName(),userBank.getCardNo().substring(userBank.getCardNo().length()-4)),2);
        if (!result.success()) {
            SystemError.wrapBs("500",result.getMessage());
        }
        if(mobaoWithholdingService.getWithdrawRecordWaitCountByUid(uid)>0 || !withholdingCreate.isWait()){
            // 银行卡提现操作
            try {
                if(StringHandler.getInt(Config.pp.get("wallet.withholding.task.open"),0)==0) {
                    com.alibaba.fastjson.JSONObject data = MobaoPay.withdraw(ip, key, withholdingCreate, userBank);
                    if (data.getString("orderStatus").equals("00")) {
                        String orderOutNo = data.getString("orderOutNo");
                        if(StringHandler.isEmpty(orderOutNo)){
                            mobaoWithholdingService.orderOutNoUpdate(record.id,orderOutNo,"",PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode(),dayKey);
                        }
                        //提现成功扣除冻结金额
//                        PayManager.accountModify(record.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, record.getAmount(), StringHandler.getString(record.getUserId()));
//                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                        Redis.key.increment(key);
                        Redis.key.setKeyTimeout(key, 86400L);
                        Redis.key.increment(freeKey);
                        Redis.key.setKeyTimeout(freeKey, 86400L);
                    } else if (data.getString("orderStatus").equals("09")) {
                        Redis.key.increment(freeKey);
                        Redis.key.setKeyTimeout(freeKey, 86400L);
                    } else {
                        //提现失败退回余额
                        PayManager.accountModify(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), data.getString("remark"),2);
                        // 保存提现记录
                        record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                        record.setRemark(data.getString("remark"));
                        mobaoWithholdingService.saveWithdrawRecord(record);
                        SystemError.wrapBs("400", "提现失败,请核对并修改正确的信息后再试");
                    }
                }
                // 保存提现记录
                mobaoWithholdingService.saveWithdrawRecord(record);
            } catch (Exception e) {
                //提现失败退回余额
                PayManager.accountModify(uid, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), e.getMessage(),2);
                // 保存提现记录
                record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_EXC.getCode());
                record.setRemark(e.getMessage());
                mobaoWithholdingService.saveWithdrawRecord(record);
                Logger.error("提现失败:",e);
                SystemError.wrapBs("400","提现失败，请核对并修改正确的信息后再试.");
            }
        }else {
            // 保存提现记录
            record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode());
            mobaoWithholdingService.saveWithdrawRecord(record);
            record.setWithdrawStatus(PayEnum.WithdrawWaitStatus.APPLY_WITHDRAWAL.getCode());
            record.setCardToken(userBank.getCardToken());
            record.setIp(ip);
            mobaoWithholdingService.saveWithdrawRecordWait(record);
        }
        Redis.str.set(limitKey,"1",StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time")));
        return ResponseHandler.success(withholdingCreate.getRequestId());
    }
    /**
     * @param uid
     * @param withholdingCreate
     * @param record
     * @param limitKey
     * @作者: dhf
     * @名称:银盛提现
     * @时间: 2022/7/18 16:41
     * @备注:
     * @返回值: java.lang.String
     */
    public String ysWithholding(long uid, MobaoWithholdingCreate withholdingCreate, WithdrawRecordWait record, String ip, String linkId, String limitKey) {
        Map<String, Object> map = new HashMap<>();
        int dayKey = StringHandler.getInt(DateUtil.getYYMMDD());
        String key = UserKey.withholdingCreateKey(dayKey, uid);
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_WITHDRAW);
            // 动账操作
            Result<?> result = PayManager.accountModify(uid, PayEnum.AccountFlowType.APPLY_FOR_WITHDRAWAL, record.getAmount(),
                String.format("余额提现-到%s(%s)", record.getBankName(), record.getCardNo().substring(record.getCardNo().length() - 4)),2);
            if (!result.success()) {
                SystemError.wrapBs("500", result.getMessage());
            }
            if (!withholdingCreate.isWait()) {
                if(StringHandler.getInt(Config.pp.get("wallet.withholding.task.open"),0)==0) {
                    record.taskType = 1;
                    //提现申请
                    UserMerchant userMerchant = yinShengService.userMerchant(uid + "");
                    // 组装业务参数
                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("requestNo", withholdingCreate.getRequestId());
                    requestMap.put("merchantNo", userMerchant.merchantNo);//银盛商户号
                    requestMap.put("amount", StringHandler.fenToYuan(withholdingCreate.getArrivalAmount()));//提现金额，单位：元
                    if (StringHandler.getInt(Config.pp.get("ys.pay.test.open"), 0) == 1) {
                        String testUser = StringHandler.getString(Config.pp.get("ys.pay.test.user"), "");
                        if (StringHandler.isNotEmpty(testUser)) {
                            String testUserList[] = testUser.split(",");
                            for (String str : testUserList) {
                                if (StringHandler.getLong(str) == uid)
                                    requestMap.put("amount", "0.01");
                            }
                        }
                    }
                    requestMap.put("linkId", linkId);//绑卡标识，提现银行卡对应的绑卡标识
                    requestMap.put("remark", "蜂省优选转账");//银行附言
                    requestMap.put("notifyUrl", withholdingCreate.ys_otifyUrl);//提现结果异步通知地址，为空则不通知
                    RequestData requestData = new RequestData(requestMap);
                    String callback = yinShengClient.requestStrApi(requestData);
                    Map<String, Object> obj = JsonUtil.jsonToBean(callback, Map.class);
                    String remark = "";
                    boolean isTrue = true;
                    String authSn = "";
                    if (!obj.get("code").equals("SYS000")) {
                        remark = "银盛提现失败:" + StringHandler.getString(obj.get("msg"));
                        log.error(remark);
                        isTrue = false;
                    } else {
                        if (StringHandler.isNotEmpty(StringHandler.getString(obj.get("bizResponseJson")))) {
                            Map<String, Object> bizResponseJson = JsonUtil.jsonNullToBean(JsonUtil.toJson(obj.get("bizResponseJson")), Map.class);
                            if (bizResponseJson.get("subCode").equals("COM000")) {
                                authSn = StringHandler.getString(bizResponseJson.get("authSn"));
                            } else if (bizResponseJson.get("subCode").equals("COM004")) {
                                authSn = StringHandler.getString(bizResponseJson.get("authSn"));
                            } else {
                                remark = "银盛提现失败:" + StringHandler.getString(bizResponseJson.get("subMsg"));
                                log.error(remark);
                                isTrue = false;
                            }
                        } else {
                            remark = "银盛提现失败:返回信息为空";
                            log.error(remark);
                            isTrue = false;
                        }
                    }
                    boolean finalIsTrue = isTrue;
                    String finalAuthSn = authSn;
                    String finalRemark = remark;
                    int a = transactionTemplate.execute(e -> {
                        if (!finalIsTrue) {
                            riskService.saveRisk(new Risk(record.userId, Convert.objToStr(record)));
                            int ii = mobaoWithholdingService.withholdingStatus(record.id,PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
                            if(ii<0){
                                log.error("提现打款任务-修改提现失败状态失败" + JsonUtil.toJson(record),record.id);
                                return 0;
                            }
                            Result<?> result2 = PayManager.accountModify(record.userId, PayEnum.AccountFlowType.WITHDRAWAL_FAIL, record.getAmount(), finalRemark,1);
                            if (!result2.success()) {
                                log.error("提现打款任务-银盛提现还原金额失败" + JsonUtil.toJson(record),result2.getMessage(),record.id);
                                return 0;
                            }
                        } else {
                            if (record.fee > 0) {
                                //记录手续费
                                mobaoWithholdingService.insertSxf(record.orderNo, record.userId, record.orderNo, record.amount, record.fee, DateHandler.getLongFormatDate(), 3, finalRemark);
                            }
                        }
                        // 保存提现记录
                        mobaoWithholdingService.saveWithdrawRecord(record);
                        Redis.key.increment(key);
                        Redis.key.setKeyTimeout(key, 86400L);
                        map.put("authSn", finalAuthSn);
                        map.put("requestNo", withholdingCreate.getRequestId());
                        return 1;
                    });
                    if(a<=0){
                        return ResponseHandler.error("500","提现失败");
                    }
                }else
                    mobaoWithholdingService.saveWithdrawRecord(record);
                    map.put("authSn", "");
                    map.put("requestNo", withholdingCreate.getRequestId());{
                }
            } else {
                // 保存提现记录
                record.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode());
                mobaoWithholdingService.saveWithdrawRecord(record);
                mobaoWithholdingService.saveWithdrawRecordWait(record);
                record.setIp(ip);
                mobaoWithholdingService.saveWithdrawRecordWait(record);
            }

        Redis.str.set(limitKey, "1", StringHandler.getInt(Config.pp.get("wallet.withholding.interval.time")));
        return ResponseHandler.success(map);
    }

    /**
     * 接收提现状态的回调
     *
     * @param notify
     * @return
     */
    @RequestMapping("send")
    public String send(@RequestBody Notify notify) {
//        System.err.println("提现回调"+ JSON.toJSONString(notify));
        WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(notify.getMerchTradeNo());
        if(StringHandler.isEmpty(withdrawRecord)){
            Logger.info("提现回调给到处理中订单--信息为空");
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        if(withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode())){
            Logger.info("提现回调给到处理中订单--该订单已完成");
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        if(withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_HANDLE.getCode())
                || withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode())){
            withdrawRecord.setDayKey(DateUtil.getYYMMDD());
            if(notify.getOrderStatus().equals("00")){
                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                int i = mobaoWithholdingService.updateWithdrawRecordByOrderId(withdrawRecord);
                if(i <= 0) {
                    Logger.info("提现回调给到处理中订单--该订单已处理");
                    return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
                }
                //提现成功扣除冻结金额
                PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, withdrawRecord.getAmount(), StringHandler.getString(withdrawRecord.getUserId()),1);
                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                if(withdrawRecord.fee>0) {
                    //记录手续费
                    mobaoWithholdingService.insertSxfMb(withdrawRecord.orderNo, withdrawRecord.userId, withdrawRecord.orderNo, withdrawRecord.amount, withdrawRecord.fee, DateHandler.getLongFormatDate(), 2, "提现手续费");
                }
            }else if(notify.getOrderStatus().equals("09")){
                Logger.info("提现回调给到处理中订单:",notify.getMerchTradeNo());
            }
//            else {
//                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
//                mobaoWithholdingService.updateWithdrawRecordByOrderId(withdrawRecord);
//                //提现失败退回余额
//                PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_FAIL, withdrawRecord.getAmount(), "");
//                //次数-1
//                String key = UserKey.withholdingCreateKey(withdrawRecord.getDayKey(), withdrawRecord.getUserId());
//                Redis.key.increment(key, -1);
//                String freeKey = UserKey.withholdingFreeKey(withdrawRecord.getDayKey(), withdrawRecord.getUserId());
//                Redis.key.increment(freeKey, -1);
//            }
        }
        return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
    }

    @RequestMapping("task/send")
    public String taskSend(@RequestBody Notify notify) {
        log.info("提现回调"+ JSON.toJSONString(notify));
        WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(notify.getMerchTradeNo());
        if(StringHandler.isEmpty(withdrawRecord)){
            Logger.info("提现回调给到处理中订单--信息为空");
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        if(withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode())){
            Logger.info("提现回调给到处理中订单--该订单已完成");
            return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
        }
        if(withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_HANDLE.getCode())
                || withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode())){
            withdrawRecord.setDayKey(DateUtil.getYYMMDD());
            if(notify.getOrderStatus().equals("00")){
                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                int i = mobaoWithholdingService.updateWithdrawRecordTask(withdrawRecord);
                if(i <= 0) {
                    Logger.info("提现回调给到处理中订单--该订单已处理");
                    return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
                }
                //提现成功扣除冻结金额
                PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_SUCCESS, withdrawRecord.getAmount(), StringHandler.getString(withdrawRecord.getUserId()),2);
                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode());
                if(withdrawRecord.fee>0) {
                    //记录手续费
                    mobaoWithholdingService.insertSxfMb(withdrawRecord.orderNo, withdrawRecord.userId, withdrawRecord.orderNo, withdrawRecord.amount, withdrawRecord.fee, DateHandler.getLongFormatDate(), 2, "提现手续费");
                }
            }else if(notify.getOrderStatus().equals("09")){
                Logger.info("提现回调给到处理中订单:",notify.getMerchTradeNo());
            }
//            else {
//                withdrawRecord.setWithdrawStatus(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode());
//                mobaoWithholdingService.updateWithdrawRecordByOrderId(withdrawRecord);
//                //提现失败退回余额
//                PayManager.accountModify(withdrawRecord.getUserId(), PayEnum.AccountFlowType.WITHDRAWAL_FAIL, withdrawRecord.getAmount(), "");
//                //次数-1
//                String key = UserKey.withholdingCreateKey(withdrawRecord.getDayKey(), withdrawRecord.getUserId());
//                Redis.key.increment(key, -1);
//                String freeKey = UserKey.withholdingFreeKey(withdrawRecord.getDayKey(), withdrawRecord.getUserId());
//                Redis.key.increment(freeKey, -1);
//            }
        }
        return JSON.toJSONString(MapHandler.initMap("returnCode","1","returnMsg","SUCCESS"));
    }
    /**
     * 提现查询
     *
     * @param withholdingQuery
     * @return
     */
    @RequestMapping("query")
    public String query(MobaoWithholdingCreate withholdingQuery) {
        withholdingQuery.payChannel=StringHandler.getString(Config.pp.get("ys.user.pay.channel"),"ys");
        Map<String,Object> res = new HashMap<>();
        WithdrawRecord withdrawRecord = mobaoWithholdingService.getWithdrawRecordByOrderId(withholdingQuery.getRequestId());
        if(StringHandler.isEmpty(withdrawRecord)){
            SystemError.wrapBs("400","提现订单号不存在");
        }
        if(withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_WAIT.getCode())){
            res.put("status", "提现待审核");
        }else if (withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_SUCCESS.getCode())) {
            res.put("status", "提现成功");
        }else if (withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.APPLY_WITHDRAWAL.getCode())) {
            res.put("status", "提现待处理:提现结果请到交易明细进行查看");
        }else if (withdrawRecord.getWithdrawStatus().equals(PayEnum.WithdrawStatus.WITHDRAWAL_FAIL.getCode())) {
            res.put("status", "提现失败:"+(withdrawRecord.getRemark().contains("|")?withdrawRecord.getRemark().split("|")[1]:withdrawRecord.getRemark()));
        }
        res.put("remark", String.format("预计%s前到账", LocalDateTime.now().plusHours(2).format(DateTimeFormatter.ofPattern("M-dd HH:mm"))));
        res.put("bankCardNumber", withdrawRecord.getCardNo().substring(withdrawRecord.getCardNo().length()-5));
        res.put("bankName", withdrawRecord.getBankName());
        res.put("fee", StringHandler.fenToYuan(StringHandler.getString(withdrawRecord.getAmount())));
        return ResponseHandler.success(res);
    }

}
